<script setup lang='ts'>
import type { UploadChangeParam, UploadFile } from 'ant-design-vue'
import { EyeOutlined, PlusOutlined } from '@ant-design/icons-vue'
import { listByIds } from '@/api/system/oss'
import type { OssVO } from '@/api/system/oss/types'
import { propTypes } from '@/utils/propTypes'
import { globalHeaders } from '@/utils/request'

const props = defineProps({
  modelValue: [String, Object, Array],
  // 图片数量限制
  limit: propTypes.number.def(5),
  // 大小限制(MB)
  fileSize: propTypes.number.def(5),
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array<string>,
    default: () => ['png', 'jpg', 'jpeg'],
  },
  listType: {
    type: String,
    default: 'picture-card',
  },
  otherTip: {
    type: String,
    default: '',
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true,
  },
  showUploadList: {
    type: Boolean,
    default: true,
  },
})
const emit = defineEmits(['update:modelValue', 'success', 'remove'])
const imageUpload = ref()
const loading = ref<boolean>(false)
const message = useMessage()
const AntLoading = useLoading({ text: '正在上传图片，请稍候...' })
const number = ref(0)
const uploadList = ref<any[]>([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const baseUrl = import.meta.env.VITE_APP_BASE_API
const uploadImgUrl = ref(`${baseUrl}/resource/oss/upload`) // 上传的图片服务器地址
const headers = ref(globalHeaders())

const fileList = ref<any[]>([])
const showTip = computed(
  () => props.isShowTip && (props.fileType || props.fileSize),
)

watch(() => props.modelValue, async (val) => {
  if (val && !val.includes('http')) {
    // 首先将值转为数组
    let list: OssVO[] = []
    if (Array.isArray(val)) {
      list = val as OssVO[]
    }
    else {
      const res = await listByIds(val as string)
      list = res.data
    }
    // 然后将数组转为对象数组
    // eslint-disable-next-line style/multiline-ternary
    fileList.value = list ? list.map((item) => {
      // 字符串回显处理 如果此处存的是url可直接回显 如果存的是id需要调用接口查出来
      let itemData
      if (typeof item === 'string') {
        itemData = { name: item, url: item }
      }
      else {
        // 此处name使用ossId 防止删除出现重名
        itemData = { name: item.ossId, url: item.url, ossId: item.ossId }
      }
      return itemData
    }) : []
  }
  else {
    fileList.value = []
    return []
  }
}, { deep: true, immediate: true })

/** 上传前loading加载 */
function handleBeforeUpload(file: any) {
  let isImg = false
  if (props.fileType.length) {
    let fileExtension = ''
    if (file.name.lastIndexOf('.') > -1)
      fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1)

    isImg = props.fileType.some((type: any) => {
      if (file.type.includes(type))
        return true
      if (fileExtension && fileExtension.includes(type))
        return true
      return false
    })
  }
  else {
    isImg = file.type.includes('image')
  }
  if (!isImg) {
    message.error(`文件格式不正确, 请上传${props.fileType.join('/')}的图片!`)
    return false
  }
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize
    if (!isLt) {
      message.error(`上传头像图片大小不能超过 ${props.fileSize} MB!`)
      return false
    }
  }
  if (props.limit > 1) {
    if (fileList.value.length >= props.limit) {
      message.error(`上传文件数量不能超过 ${props.limit} 个!`)
      return false
    }
  }
  AntLoading.open()
  number.value++
}

// 文件个数超出
function handleExceed() {
  message.error(`上传文件数量不能超过 ${props.limit} 个!`)
}

// 上传成功回调
function handleUploadSuccess(info: UploadChangeParam) {
  if (info.file.status === 'uploading') {
    loading.value = true
    return
  }
  if (info.file.status === 'done') {
    // Get this url from response in real world.
    console.log(info)
    const res = info.file.response
    console.log(res)
    if (res.code === 200) {
      uploadList.value.push({ name: res.data.fileName, url: res.data.url, ossId: res.data.ossId })
      uploadedSuccessfully()
    }
    else {
      number.value--
      AntLoading.close()
      message.error(res.msg)
      uploadedSuccessfully()
    }
    AntLoading.close()
  }
  if (info.file.status === 'error')
    message.error('文件上传失败')
  AntLoading.close()
}

// 删除图片
function handleDelete(file: UploadFile): boolean {
  const findex = fileList.value.map(f => f.name).indexOf(file.name)
  if (findex > -1 && uploadList.value.length === number.value) {
    fileList.value.splice(findex, 1)
    emit('update:modelValue', listToString(fileList.value))
    emit('success', listToString(fileList.value))
    emit('remove', findex)
    return false
  }
  return true
}

// 上传结束处理
function uploadedSuccessfully() {
  if (number.value > 0 && uploadList.value.length === number.value) {
    fileList.value = fileList.value.filter(f => f.url !== undefined).concat(uploadList.value)
    uploadList.value = []
    number.value = 0
    emit('update:modelValue', listToString(fileList.value))
    emit('success', listToString(fileList.value))
    AntLoading.close()
  }
}

// 上传失败
function handleUploadError() {
  message.error('上传图片失败')
  AntLoading.close()
}
async function handlePictureCardPreview(file: UploadProps['fileList'][number], event) {
  console.log('开始预览', file, event)
  if (!file.url && !file.preview)
    file.preview = (await getBase64(file.originFileObj)) as string

  dialogImageUrl.value = file.url || file.preview
  dialogVisible.value = true
}

// 对象转成指定字符串分隔
function listToString(list: any[], separator?: string) {
  let strs = ''
  separator = separator || ','
  for (const i in list) {
    if (undefined !== list[i].ossId && list[i].url.indexOf('blob:') !== 0)
      strs += list[i].ossId + separator
  }
  console.log(strs)
  return strs !== '' ? strs.substring(0, strs.length - 1) : ''
}
</script>

<template>
  <div class="component-upload-image">
    <a-upload
      ref="imageUpload"
      v-model:file-list="fileList"
      :action="uploadImgUrl"
      :list-type="listType"
      :before-upload="handleBeforeUpload"
      :max-count="limit"
      :on-error="handleUploadError"
      :on-exceed="handleExceed"
      :show-file-list="true"
      :show-upload-list="showUploadList"
      :headers="headers"
      class="bh-image-upload"
      @remove="handleDelete"
      @preview="handlePictureCardPreview"
      @change="handleUploadSuccess"
    >
      <template #iconRender="file">
        <div @click.stop="handlePictureCardPreview(file)">
          <EyeOutlined />
        </div>
      </template>
      <slot v-if="fileList.length < limit || limit === 1">
        <PlusOutlined style="font-size: 18px;color: #c3c3c3" />
      </slot>
    </a-upload>
    <!-- 上传提示 -->
    <div v-if="showTip" class="el-upload__tip">
      请上传
      <template v-if="fileSize">
        大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b>
      </template>
      <template v-if="fileType">
        格式为 <b style="color: #f56c6c">{{ fileType.join('/') }}</b>
      </template>
      的文件 {{ otherTip }}
    </div>

    <a-modal v-model:open="dialogVisible" :mask-closable="false" :keyboard="false" :footer="null" title="预览" width="800px" append-to-body>
      <img :src="dialogImageUrl" style="display: block; max-width: 100%; margin: 0 auto">
    </a-modal>
  </div>
</template>

<style scoped lang='less'>
// .el-upload--picture-card 控制加号部分

:deep(.bh-image-upload) {
  .ant-upload-list-item-action:hover {
    background-color: transparent !important;
  }

  .ant-upload-list-item {
    padding: 0px !important;
    img {
      border-radius: 8px;
    }
  }
  &.ant-upload-wrapper.ant-upload-picture-card-wrapper .ant-upload-list.ant-upload-list-picture-card .ant-upload-list-item::before {
    width: 100%;
    height: 100%;
  }
}
</style>
